/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package chelydra.sharelydra.client.file;

/**
 *
 * @author Enhancer
 */

import chelydra.sharelydra.client.Core;
import chelydra.sharelydra.client.database.DatabaseManager;
import chelydra.sharelydra.client.misc.DefaultValue;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileManager {

/*
 * return an array countaining length byte of the input file,
 * starting from the offset startOffset
 */
public static byte[] sliceReader(String fileName, int startOffset, int length){
     byte[] buffer = new byte[length];
     try {
         RandomAccessFile sourceFile = new RandomAccessFile(fileName, "r");
         System.out.println("reading file \""+fileName+"\"");
         System.out.println("file total length "+sourceFile.length());
         sourceFile.seek(new Integer(startOffset).longValue());
         sourceFile.read(buffer);
         sourceFile.close();
     } catch (IOException iOException) {
         iOException.printStackTrace();
     }
     int endOffset = startOffset + length - 1;
     System.out.println("Slice taken ["+startOffset+" "+endOffset+"] size : "+length +" bytes");
     return buffer;
}

/*
 * stock in the file named the array of bytes at the right offset
 */
public static void sliceWriter(String fileName, int startOffset, byte[] data){
    int length=data.length;
    try {
        RandomAccessFile destinationFile = new RandomAccessFile(fileName, "rw");
        System.out.println("writing file \""+fileName+"\"");
        destinationFile.seek(new Integer(startOffset).longValue());
        destinationFile.write(data);
        destinationFile.close();
    } catch (IOException iOException) {
         iOException.printStackTrace();
    }
    int endOffset = startOffset + length - 1;
    System.out.println("Slice writen ["+startOffset+" "+endOffset+"] size : "+length +" bytes");
}

public static byte[] getHash(byte[] data){
    byte[] hash = null;
    try {
        hash = MessageDigest.getInstance("MD5").digest(data);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    return hash;
}

public static void listing(String directory){
     File directoryToScan = new File(directory);
     if (directoryToScan.isFile()){
         String name = directoryToScan.getName();
         if (!(name.startsWith(".") || name.equalsIgnoreCase("Thumbs.db"))){
             String path = directoryToScan.getParent();
             String size = new Long(directoryToScan.length()).toString();
             String[] table={path, name, size};
             DatabaseManager dm = Core.getApplication().getDatabaseManager();
             dm.addNewFile(name, path, Integer.parseInt(size));
             printTable(table);
         }
     } else {
         Collection<String[]> listOfFiles = new Vector();
         File[] files = null;
         System.out.println("directory to list :" + directory);
         files = directoryToScan.listFiles();
         System.out.println("there are "+files.length+" files and folders \n");
         int i;
         for(i=0;i<files.length;i++){
             if (files[i].isFile()){
                 String name = files[i].getName();
                 if (!(name.startsWith(".") || name.equalsIgnoreCase("Thumbs.db"))){
                     String path = files[i].getParent();
                     String size = new Long(files[i].length()).toString();
                     String[] table={path, name, size};
                     listOfFiles.add(table);
                     //DatabaseManager dm = new DatabaseManager();
                     //dm.addNewFile(name, path, Integer.parseInt(size));
                     printTable(table);
                 }

             }else{//it's a sub directory
                 listing(files[i].getAbsolutePath());
             }
         }
         DatabaseManager dm = Core.getApplication().getDatabaseManager();
         dm.addNewFolder(listOfFiles);
     }
}


public static void printTable(String[] table){
    String[] tab = table;
    System.out.println("");
    System.out.println("----------------");
    System.out.println("url    : "+tab[0]);
    System.out.println("----------------");
    System.out.println("nom    : "+tab[1]);
    System.out.println("----------------");
    System.out.println("taille : "+tab[2]);
    System.out.println("----------------");
    System.out.println("");
}

public static String[] getListOfFile(){
    String[] listOfFile=null;
    //access to the database
    return listOfFile;
}

public String getPath(String fileName){
    String path=null;
    //access to the database
    return path;
}

public static void FirstUpdateFileUI(){
    //TO DO : Delete the former files from the DataBase
    DatabaseManager dm = Core.getApplication().getDatabaseManager();
    dm.deleteSharedFileList();
    FileManager.listing(DefaultValue.DefaultSharedFolder);
    Collection<Map<String,String>> files = dm.getFileList();
    Core.getApplication().getView().updateSharedFiles(files);
}

public static void updateFileUI(){
    DatabaseManager dm = Core.getApplication().getDatabaseManager();
    Collection<Map<String,String>> files = dm.getFileList();
    Core.getApplication().getView().updateSharedFiles(files);
}

public static void stopSharingFile(String filename){
    DatabaseManager dm = Core.getApplication().getDatabaseManager();
    dm.deleteFile(filename);
    System.out.println("the database manager has removed \""+filename+"\" from the database");
}

}


